package cn.backflow.admin.repository;

import cn.backflow.admin.entity.User;
import cn.backflow.data.pagination.Page;
import cn.backflow.data.pagination.PageRequest;
import cn.backflow.data.repository.BaseMyBatisRepository;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserRepository extends BaseMyBatisRepository<User, Integer> {

    @Override
    public int saveOrUpdate(User user) {
        return user.getId() == null ? insert(user) : update(user);
    }

    public Page<User> findByPageRequest(PageRequest pageRequest) {
        return pageQuery("User.paging", pageRequest);
    }

    public Long count() {
        return sqlSession.selectOne("User.count");
    }

    public List<User> search(PageRequest pr) {
        pr.getFilters().put("_offset_", pr.getPageOffset());
        pr.getFilters().put("_limit_", pr.getPageSize());
        pr.getFilters().put("_sort_", pr.getSortColumns());
        return sqlSession.selectList("User.search", pr.getFilters());
    }

    public Page<User> query(PageRequest pr) {
        return pageQuery("User.query", pr);
    }

    /**
     * 分离部门关联
     *
     * @param id 部门ID
     */
    public int separateDepartment(Integer id) {
        return sqlSession.update("User.separateDepartment", id);
    }

    /**
     * 按唯一属性查找
     *
     * @param identity 唯一属性（id, name, email, phone）
     */
    public User getByIdentity(Object identity) {
        return sqlSession.selectOne("User.getByIdentity", identity);
    }

    /**
     * 按唯一属性选择性更新 (id, name, email, phone）
     */
    public int updateByIdentitySelective(User user) {
        return sqlSession.selectOne("User.updateByIdentitySelective", user);
    }
}